import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fake_wechat/fake_wechat.dart';
import 'package:flutter/material.dart';
import 'package:alipay_kit/alipay_kit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter/services.dart';
import '../../event/VipEven.dart';
// import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';

///
// * 订单支付页面
// * @author weimengmeng
// * @date 2019-08-30 17:08
// * 包括微信支付和支付宝支付
///
class OrderPayPage extends StatefulWidget {
  String orderId, orderNum, totalMoney, title;

  OrderPayPage(
      {Key key,
      @required this.orderId,
      @required this.orderNum,
      @required this.totalMoney,
      this.title})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return OrderPayView(orderId, orderNum, totalMoney);
  }
}

class OrderPayView extends State<OrderPayPage> {
  String orderId, orderNum, totalMoney, token;
  int groupValue = 1;
  Wechat _wechat = Wechat()
    ..registerApp(appId: WX_APPID, universalLink: "https://do.com/");
  StreamSubscription<WechatPayResp> _pay;
  OrderPayView(this.orderId, this.orderNum, this.totalMoney);
  bool isShow = true;

  static const bool _ALIPAY_USE_RSA2 = true;
  static const String _ALIPAY_APPID = 'your alipay appId'; // 支付/登录
  static const String _ALIPAY_PID = 'your alipay pid'; // 登录
  static const String _ALIPAY_TARGETID = 'your alipay targetId'; // 登录
  static const String _ALIPAY_PRIVATEKEY =
      'your alipay rsa private key(pkcs1/pkcs8)'; // 支付/登录
  Alipay _alipay = Alipay();
  StreamSubscription<AlipayResp> _apay;
  StreamSubscription<AlipayResp> _auth;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "订单支付",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: new SingleChildScrollView(
        child: new Container(
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                color: divideColor,
                height: ScreenUtil.getInstance().setWidth(DP_20),
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '订单编号',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(
                      '$orderNum',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '订单金额',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(
                      '$totalMoney',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '优惠金额',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(
                      '0.00',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '实际支付',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(MONEY + '$totalMoney',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: mainColor))
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_10),
                    ScreenUtil.getInstance().setWidth(DP_30)),
                child: Text(
                  '选择支付方式 ',
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                ),
              ),
              new Container(
                alignment: Alignment.centerRight,
                child: new Column(
                  children: <Widget>[
                    new Container(
                      color: Colors.white,
                      child: new Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Image.asset(
                              'images/user_icon_order_rufund.png',
                              width: ScreenUtil.getInstance().setWidth(DP_60),
                              height: ScreenUtil.getInstance().setWidth(DP_60),
                            ),
                          ),
                          Expanded(
                            flex: 4,
                            child: Text('余额支付',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                          ),
                          Checkbox(
                              value: groupValue == 0,
                              activeColor: mainColor,
                              // groupValue: groupValue,
                              onChanged: (T) {
                                setState(() {
                                  groupValue = 0;
                                });
                              }),
                        ],
                      ),
                    ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    new Container(
                      color: Colors.white,
                      child: new Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Image.asset(
                              'images/icon_ipay.png',
                              width: ScreenUtil.getInstance().setWidth(DP_60),
                              height: ScreenUtil.getInstance().setWidth(DP_60),
                            ),
                          ),
                          Expanded(
                            flex: 4,
                            child: Text('支付宝支付',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                          ),
                          Checkbox(
                              value: groupValue == 1,
                              activeColor: mainColor,
                              // groupValue: groupValue,
                              onChanged: (T) {
                                setState(() {
                                  groupValue = 1;
                                });
                              }),
                        ],
                      ),
                    ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    // Offstage(
                    //   offstage: false,
                    //   child: new Container(
                    //     color: Colors.white,
                    //     child: new Row(
                    //       children: <Widget>[
                    //         Expanded(
                    //           flex: 1,
                    //           child: Image.asset(
                    //             'images/icon_wechat.png',
                    //             width: ScreenUtil.getInstance().setWidth(DP_60),
                    //             height:
                    //                 ScreenUtil.getInstance().setWidth(DP_60),
                    //           ),
                    //         ),
                    //         Expanded(
                    //           flex: 4,
                    //           child: Text('微信支付',
                    //               style: TextStyle(
                    //                   color: Colors.black,
                    //                   fontSize: ScreenUtil.getInstance()
                    //                       .setSp(NORMAL_FONT_SIZE))),
                    //         ),
                    //         CircularCheckBox(
                    //             value: groupValue == 2,
                    //             activeColor: mainColor,
                    //             onChanged: (T) {
                    //               setState(() {
                    //                 groupValue = 2;
                    //               });
                    //             }),
                    //       ],
                    //     ),
                    //   ),
                    // )
                  ],
                ),
              ),
              new Container(
                width: double.infinity,
                alignment: Alignment.center,
                height: ScreenUtil.getInstance().setWidth(DP_80),
                margin: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_100),
                    ScreenUtil.getInstance().setWidth(DP_80),
                    ScreenUtil.getInstance().setWidth(DP_100),
                    0),
                decoration: new BoxDecoration(
                    color: mainColor,
                    borderRadius: BorderRadius.circular(
                        ScreenUtil.getInstance().setWidth(DP_80))),
                child: new FlatButton(
                  child: new Padding(
                    padding: EdgeInsets.all(0.0),
                    child: new Text(
                      "立即支付",
                      style: new TextStyle(
                          color: Colors.white,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                  ),
                  onPressed: () async {
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (_) {
                          return new NetLoadingDialog(
                            loadingText: "支付中...",
                            bgColor: Color.fromARGB(255, 0, 0, 0),
                            requestCallBack: null,
                            outsideDismiss: false,
                          );
                        });
                    getOrderForm();
                    // var result = await FlutterAlipay.pay("you pay info from server");
                    // print(result);
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  getOrderForm() async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = widget.orderId;
    map['pay_method'] =
        groupValue == 0 ? "balance" : groupValue == 1 ? "alipay" : "wxpay";
    // map['sign_type']=SignType.GET_PAY_FORM;
    // return ;
    // print(map);
    Navigator.of(context).pop(1);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.VipShopPayFormUrl, data: data);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(userMap);
    if (code == 1) {
      if (groupValue == 0) {
        //  APPLIC.eventBus.fire(VipEven());
        APPLIC.eventBus.fire(LoginEvent());
        showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return new SimpleDialog(
                title: new Text('购买成功，请耐心等待1分钟处理'),
                children: <Widget>[
                  new SimpleDialogOption(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.popAndPushNamed(context, '/');
                    },
                  ),
                ],
              );
            });
        // print(userMap);
      } else {
        if (groupValue == 1) {
          _alipay.payOrderSign(orderInfo: userMap['data']['pay_parameters']);
        } else {
          print(userMap['data']['pay_parameters']);
          String str = json.encode(userMap['data']['pay_parameters']);
          Map map = json
              .decode(str.substring(1, str.length - 1).replaceAll("\\", ""));
          print(map['appid']);
          _wechat.pay(
            appId: WX_APPID,
            partnerId: map['partnerid'],
            prepayId: map['prepayid'],
            package: map['package'],
            nonceStr: map['noncestr'],
            timeStamp: map['timestamp'].toString(),
            sign: map['sign'],
          );
        }
      }
    } else {
      Fluttertoast.showToast(msg: msg);
    }
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
    _pay = _wechat.payResp().listen(_listenPay);
    checkWx();

    _apay = _alipay.payResp().listen(_listenaPay);
    _auth = _alipay.authResp().listen(_listenAuth);
  }

  void _listenaPay(AlipayResp resp) {
    String content = 'pay: ${resp.resultStatus} - ${resp.result}';

    switch ('${resp.resultStatus}') {
      case "9000":
        // APPLIC.eventBus.fire(VipEven());
        APPLIC.eventBus.fire(LoginEvent());
        //  Fluttertoast.showToast(msg: '购买成功，请耐心等待1分钟处理');
        showDialog(
            context: context,
            builder: (context) {
              return new SimpleDialog(
                title: new Text('购买成功，请耐心等待1分钟处理'),
                children: <Widget>[
                  new SimpleDialogOption(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.popAndPushNamed(context, '/');
                    },
                  ),
                ],
              );
            });

        break;
      case "8000":
        Fluttertoast.showToast(msg: "正在处理中");
        break;
      case "4000":
        Fluttertoast.showToast(msg: "订单支付失败");
        break;
      case "6001":
        Fluttertoast.showToast(msg: "取消支付");
        break;
      case "6002":
        Fluttertoast.showToast(msg: "网络连接出错");
        break;
      default:
    }
    // _showTips('支付', content);
  }

  void _listenAuth(AlipayResp resp) {
    String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    _showTips('授权登录', content);
  }

  void _showTips(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(content),
        );
      },
    );
  }

  checkWx() async {
    if (await _wechat.isWechatInstalled()) {
      setState(() {
        isShow = false;
      });
    } else {
      setState(() {
        isShow = true;
      });
    }
  }

  void _listenPay(WechatPayResp resp) {
    String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
    print(content);
    switch (resp.errorCode.toString()) {
      case "0":
        // APPLIC.eventBus.fire(VipEven());
        APPLIC.eventBus.fire(LoginEvent());
        Fluttertoast.showToast(msg: "订单支付成功");
        Navigator.popAndPushNamed(context, '/');
        break;
      case "-1":
        Fluttertoast.showToast(msg: "支付异常");
        break;
      case "-2":
        Fluttertoast.showToast(msg: "取消支付");
        break;
    }
  }

  @override
  void dispose() {
    if (_pay != null) {
      _pay.cancel();
    }
    if (_apay != null) {
      _apay.cancel();
    }
    if (_auth != null) {
      _auth.cancel();
    }
    super.dispose();
  }
}
